package com.platform.qujia.service.impl;

import com.platform.qujia.dao.CouponActivityMapper;
import com.platform.qujia.dao.CouponInfoMapper;
import com.platform.qujia.dao.CouponIssueMapper;
import com.platform.qujia.dao.CouponUserMapper;
import com.platform.qujia.pojo.*;
import com.platform.qujia.service.CouponActivityService;
import com.platform.qujia.utils.DateUtils;
import com.platform.qujia.utils.ResultData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

@Service("couponActivityService")
@Slf4j
public class CouponActivityServiceImpl implements CouponActivityService {

    @Autowired
    private CouponActivityMapper couponActivityMapper;

    @Resource
    private CouponIssueMapper couponIssueMapper;

    @Resource
    private CouponUserMapper couponUserMapper;

    @Resource
    private CouponInfoMapper couponInfoMapper;


    @Override
    public void physicalCardSendCoupon(PayOrder payOrder) {
        try {
            List<String> couponIssueIds = new ArrayList<>();
            String activityId = this.checkCouponActivity(payOrder.getEnterpriseId().intValue(), payOrder, 0.0);
            Map<String, Object> activity = couponActivityMapper.getActivityAllByActivityId(activityId);
            BigDecimal receivedAmt;
            if (activity.isEmpty()) {
            } else {
                receivedAmt = payOrder.getAmt() != null ? BigDecimal.valueOf(payOrder.getAmt()) : BigDecimal.ZERO;
                if ((Integer) activity.get("distribution_type") == 0) {
                    BigDecimal activityThreshold = new BigDecimal(activity.get("activity_threshold").toString());
                    if (receivedAmt.compareTo(activityThreshold) >= 0) {
                        couponIssueIds = this.getIssueIdsByActivityId(activityId);
                    }
                } else if ((Integer) activity.get("distribution_type") == 1) {
                    couponIssueIds = this.getIssueIdsByActivityIdAndAmt(activityId, receivedAmt);
                }
                DrawCoupon drawCoupon = new DrawCoupon();
                List<String> mobilePhoneList = new ArrayList<>();
                mobilePhoneList.add(payOrder.getCustomerPhone());
                drawCoupon.setCouponIssueIdList(couponIssueIds);
                drawCoupon.setMobilePhoneList(mobilePhoneList);
                drawCoupon.setEnterpriseId(payOrder.getEnterpriseId().longValue()); // 添加企业ID
                ResultData result = this.sendCoupon(drawCoupon);
            }
        } catch (Exception e) {
            // 处理子方法抛出的异常
            System.out.println("消费后领券发生异常：" + e.getMessage());
        }
    }

    @Override
    public List<CouponActivity> queryList(CouponActivity couponActivity) {
        return couponActivityMapper.queryList(couponActivity);
    }

    public String checkCouponActivity(Integer enterpriseId, PayOrder payOrderInfo, Double amt) {
        BigDecimal receivedAmt = BigDecimal.valueOf(payOrderInfo.getAmt());

//        微信1支付宝2现金3银行卡4电子卡5实体卡6
        String payType = "6";

        Map<String, Object> labelParam = new HashMap<>();
        labelParam.put("mobilePhone", payOrderInfo.getCustomerPhone());
        labelParam.put("enterpriseId", Long.valueOf(enterpriseId));
//        标签
        String labelActivityIds = couponActivityMapper.checkLabelCouponActivity(labelParam);
        List<String> activityIdList = new ArrayList<>();
        Set<String> uniqueActivityIdSet = new HashSet<>();

        if(labelActivityIds!=null &&labelActivityIds!=""){
            String[] uniqueActivityIds = labelActivityIds.split(",");
            for (String activityId : uniqueActivityIds) {
                activityIdList.add(activityId);
                uniqueActivityIdSet.add(activityId);
            }
        }
//        会员级别
        String userMemberLevel = this.getAppUserGrowLevel(payOrderInfo.getCustomerPhone(), Long.valueOf(enterpriseId));
        Map<String, Object> param = new HashMap<>();
        param.put("enterpriseId", enterpriseId);
        param.put("payType", payType);
        param.put("userMemberLevel", userMemberLevel);
        param.put("activityIds", uniqueActivityIdSet);
        List<String> activityIds = new ArrayList<>();
        if (uniqueActivityIdSet.size() != 0) {
            activityIds = couponActivityMapper.checkCouponActivityOnLabel(param);
        }
        if (activityIds.size() == 0) {
            activityIds = couponActivityMapper.checkCouponActivity(param);
        }
        if (activityIds != null && !activityIds.isEmpty()) {
            Map<String, Object> thresholdParam = new HashMap<>();
            thresholdParam.put("receivedAmt", receivedAmt);
            thresholdParam.put("activityIds", activityIds);
            String activityId = couponActivityMapper.checkThresholdCouponActivity(thresholdParam);
            return activityId;
        } else {
            return "0";
        }
    }

    // 根据活动 ID 查询对应的 issue_id 列表
    public List<String> getIssueIdsByActivityId(String activityId) {
        return couponActivityMapper.getIssueIdsByActivityId(activityId);
    }

    // 根据活动 ID 查询对应的 issue_id 列表
    public List<String> getIssueIdsByActivityIdAndAmt(String activityId, BigDecimal receivedAmt) {
        // 获取满足条件的最大 threshold_amt 值
        BigDecimal thresholdAmt = couponActivityMapper.getThresholdAmtByActivityIdAndAmt(activityId, receivedAmt);

        if (thresholdAmt != null) {
            // 根据最大 threshold_amt 值获取对应的 issue_id 列表
            List<String> issueIds = couponActivityMapper.getIssueIdsByThresholdAmt(activityId, thresholdAmt);
            return issueIds;
        } else {
            // 如果 thresholdAmt 为 null，表示没有符合条件的数据
            return new ArrayList<>();
        }
    }

    public String getAppUserGrowLevel(String mobilePhone, Long enterpriseId) {
        Map<String, Object> param = new HashMap<>();
        param.put("mobilePhone", mobilePhone);
        param.put("enterpriseId", enterpriseId);
        param.put("superName", "年卡");
        String grow = new String();
        String supergrow = couponActivityMapper.getSuperGrow(param);
        if (supergrow!=null&&supergrow.equals("1")) {
            return "8";
        }
        param.put("superName", "季卡");
        supergrow = couponActivityMapper.getSuperGrow(param);
        if (supergrow!=null&&supergrow.equals("1")) {
            return "7";
        }
        param.put("superName", "月卡");
        supergrow = couponActivityMapper.getSuperGrow(param);
        if (supergrow!=null&&supergrow.equals("1")) {
            return "6";
        }
        grow = couponActivityMapper.getGrow(param);
        return grow;
    }


    public ResultData sendCoupon(DrawCoupon drawCoupon) {
        Integer activityType = drawCoupon.getActivityType();
        ResultData a = ResultData.error("优惠券手动发放失败");
        drawCoupon.setRandomFlag(System.currentTimeMillis() + RandomStringUtils.randomNumeric(7));
        List<String> couponIssueIdList = drawCoupon.getCouponIssueIdList();
        List<String> mobilePhoneList = drawCoupon.getMobilePhoneList();
        if (couponIssueIdList != null && !couponIssueIdList.isEmpty() && mobilePhoneList != null && !mobilePhoneList.isEmpty()) {


//校验
            for (String couponIssueId : couponIssueIdList) {
                for (String mobilePhone : mobilePhoneList) {
                    Map<String, String> paramMap = new HashMap<>();
                    paramMap.put("mobilePhone", mobilePhone);
                    paramMap.put("couponIssueId", couponIssueId);
                    CouponIssue souponIssue = couponIssueMapper.selectCouponIssueById(couponIssueId);
                    int userIssueGiveCount = couponUserMapper.selectUserIssueGiveCount(paramMap);
                    CouponUserGiveCount cugc = couponUserMapper.selectCouponUserGiveCount(CouponUserGiveCount.builder().mobilePhone(mobilePhone).couponIssueId(couponIssueId).randomFlag(drawCoupon.getRandomFlag()).build());
                    Integer couponinfoId = couponIssueMapper.getCouponInfoIdByIssueId(Long.parseLong(couponIssueId));
                    CouponInfo couponInfo = couponInfoMapper.selectCouponInfoById(couponinfoId);
                    if (couponInfo != null && couponInfo.getGetCouponNum() >= couponInfo.getCouponNum()) {
                        return ResultData.error("优惠券手动发放失败优惠券" + couponInfo.getCouponRemark() + "已不能再领");
                    }
                    if (souponIssue != null && userIssueGiveCount >= souponIssue.getGiveCount()) {
                        return ResultData.error("优惠券手动发放失败用户已不能再领");
                    }
                    if (souponIssue != null && userIssueGiveCount >= souponIssue.getGiveCount()) {
                        return ResultData.error("优惠券手动发放失败用户已不能再领");
                    }
                    if (souponIssue == null || !souponIssue.getStatus().equals("1")) {
                        return ResultData.error("优惠券状态不对");
                    }
                    if (cugc != null && cugc.getIssueGiveCount() + 1 >= souponIssue.getGiveLimit()) {
                        return ResultData.error("优惠券剩余数量不足");
                    } else if (1 >= souponIssue.getGiveLimit()) {
                        return ResultData.error("优惠券剩余数量不足");
                    }


                }

            }
//            使用
            int counter = 1; // 初始化计数器
            List<CouponUser> saveCouUserList = new ArrayList<>();
            List<Integer> updateTemIdsCountList = new ArrayList<>();
            for (String couponIssueId : couponIssueIdList) {
                for (String mobilePhone : mobilePhoneList) {
                    Integer couponinfoId = couponIssueMapper.getCouponInfoIdByIssueId(Long.parseLong(couponIssueId));
                    drawCoupon.setCouponIssueId(couponIssueId);

                    drawCoupon.setCouTemIds(couponinfoId.toString());
                    // 生成后三位的字符串，保证至少有三位，不足的在前面补0
                    String counterString = String.format("%03d", counter);

                    // 获取原始的 randomFlag，即去掉后三位的部分
                    String originalRandomFlag = drawCoupon.getRandomFlag().substring(0, drawCoupon.getRandomFlag().length() - 3);

                    // 构建新的 randomFlag，将原始部分与后三位替换为循环数
                    String newRandomFlag = originalRandomFlag + counterString;

                    // 更新 drawCoupon 的 randomFlag
                    drawCoupon.setRandomFlag(newRandomFlag);

                    // 增加计数器
                    counter++;
//                    CouponIssue couponIssue = couponIssueMapper.selectCouponIssueById(couponinfoId.toString());
                    CouponInfo couponInfo = couponInfoMapper.selectCouponInfoById(couponinfoId);
                    Date startTime = new Date();     //开始时间
                    Date endTime = new Date();       //结束时间

                    switch (couponInfo.getEffectiveTimeType()) {
                        case "1":   //固定时间
                            //startTime = couponTemplate.getEffectiveTimeStart();
                            endTime = couponInfo.getEffectiveTimeEnd();
                            break;
                        case "2":   //领取后有效天数
                            startTime = new Date();
                            Calendar instance = Calendar.getInstance();
                            instance.setTime(new Date());
                            instance.add(Calendar.DATE, couponInfo.getEffectiveDayNum());
                            endTime = instance.getTime();
                            break;
                    }
                    saveCouUserList.add(CouponUser.builder()
                            .mobilePhone(mobilePhone)
                            .issueId(couponIssueId)
                            .couponId(couponinfoId)
                            .couponIsUsed("0")
                            .couponNo(useMD5(drawCoupon.getEnterpriseId() + Long.toString(System.currentTimeMillis()) + Math.round((Math.random() + 1) * 1000)))
                            .enterpriseId(drawCoupon.getEnterpriseId().intValue())
                            .ccsdId(drawCoupon.getCcsdId().longValue())
                            .couponGetTime(startTime)
                            .activityType(activityType)
                            .activityName("-")
                            .randomFlag(drawCoupon.getRandomFlag())
                            .couponEffectiveTime(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",endTime))
                            .build());
                    updateTemIdsCountList.add(couponinfoId);

                    CouponUserGiveCount cugc = couponUserMapper.selectCouponUserGiveCount(CouponUserGiveCount.builder().mobilePhone(mobilePhone).couponIssueId(couponIssueId).randomFlag(drawCoupon.getRandomFlag()).build());
                    if (null != cugc) {
                        couponUserMapper.updateCouponUserGiveCount(CouponUserGiveCount.builder()
                                .randomFlag(drawCoupon.getRandomFlag())
                                .issueGiveCount(1 + cugc.getIssueGiveCount())
                                .mobilePhone(mobilePhone)
                                .couponIssueId(couponIssueId)
                                .build());
                    } else {
                        couponUserMapper.insertCouponUserGiveCount(CouponUserGiveCount.builder()
                                .randomFlag(drawCoupon.getRandomFlag())
                                .issueGiveCount(1)
                                .mobilePhone(mobilePhone)
                                .couponIssueId(couponIssueId)
                                .build());
                    }
                }
            }

            if (null != saveCouUserList && saveCouUserList.size() > 0) {
                int i = couponUserMapper.saveBatchCouponUser(saveCouUserList);
                log.info("批量保存的用户优惠券数量：" + i);
                CouponDeduction couponDeduction = new CouponDeduction();
                couponDeduction.setUpdateTemIdsCountList(updateTemIdsCountList);
                couponDeduction.setPhoneSize(mobilePhoneList.size());
                int y = couponUserMapper.updateBatchCouponTemplate(couponDeduction);
                log.info("批量更新的优惠券模板减少的模板优惠券数量：" + mobilePhoneList.size());
                a = ResultData.success("发放成功");
            } else {
                return ResultData.error("没有可以保存的优惠券");
            }


        } else {
            a = ResultData.error("缺少用户手机号或可用的优惠券");
        }
        return a;
    }

    public static String useMD5(String passWord) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(passWord.getBytes());
            return getHashString(digest);

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;

    }

    private static String getHashString(MessageDigest digest) {
        StringBuilder builder = new StringBuilder();
        for (byte b : digest.digest()) {
            builder.append(Integer.toHexString((b >> 4) & 0xf));
            builder.append(Integer.toHexString(b & 0xf));
        }
        return builder.toString().toLowerCase();
    }

}
